package com.dahuyou.types.util.huohuo;

import io.jsonwebtoken.*;

import java.util.Date;
import java.util.Map;
import java.util.function.Function;

public class JwtUtils {  
  
    private static final String SECRET_KEY = "yourSecretKeyyourSecretKeyyourSecretKeyyourSecretKeyyourSecretKeyyourSecretKeyyourSecretKeyyourSecretKeyyourSecretKey"; // 你的密钥
    private static final long JWT_EXPIRATION = 86400000; // 1天  
  
    // 生成JWT令牌
    /**
     * 指定主题
     * @param subject
     * @return
     */
    public static String generateJwt(String subject) {  
        Date now = new Date();  
        Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION);  
  
        return Jwts.builder()  
                .setSubject(subject)  
                .setIssuedAt(now)  
                .setExpiration(expiryDate)  
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)  
                .compact();  
    }

    /**
     * 指定主题和payload
     * @param subject
     * @param payloadMap
     * @return
     */
    public static String generateJwtWithPayload(String subject, Map<String, Object> payloadMap) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION);

        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .setClaims(payloadMap)
                .signWith(SignatureAlgorithm.HS512, SECRET_KEY)
                .compact();
    }

    // 解析JWT令牌  
    public static Jws<Claims> parseJwtV1(String jwt) {
//        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt).getBody();
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt);
    }

    // 解析JWT令牌
    public static Claims parseJwt(String jwt) {
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt).getBody();
    }


    // 验证JWT令牌是否有效  
    public static boolean isJwtValid(String jwt) {  
        try {  
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt);  
            return true;  
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | SignatureException | IllegalArgumentException e) {  
            // JWT已过期、不支持、格式错误、签名不匹配或参数无效  
            return false;  
        }  
    }  
  
    // 从JWT令牌中获取主题  
    public static String getSubjectFromJwt(String jwt) {  
        Claims claims = parseJwt(jwt);  
        return claims.getSubject();  
    }  
  
    // 自定义函数，用于处理JWT令牌解析后的Claims对象  
    public static <T> T processClaims(String jwt, Function<Claims, T> claimsProcessor) {  
        Claims claims = parseJwt(jwt);  
        return claimsProcessor.apply(claims);  
    }  
}